import Vue from "vue";
import axios from "axios";
import store from "@/store";

/**
 * 【指定 axios的 baseURL】
 * 则映射后端域名，通过 vue.config.js
 */
let apiBaseUrl = window.global_value.VUE_APP_API_URL || "/";
console.log("apiBaseUrl= ", apiBaseUrl);

// 创建 axios 实例
const service = axios.create({
    baseURL: apiBaseUrl, // api base_url
    timeout: 1000 * 60 * 2, // 请求超时时间
    // `withCredentials` 表示跨域请求时是否需要使用凭证
    withCredentials: true, // default =false  允许使用凭证
    headers: {"X-Requested-With": "XMLHttpRequest"}, //设置请求头为Ajax请求
});

// request interceptor
service.interceptors.request.use(
    (config) => {
        const token = Vue.ls.get(window.global_value.TOKEN_KEY);
        if (token) {
            config.headers[window.global_value.TOKEN_KEY] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

const err = (error) => {
    if (error.response) {
        let data = error.response.data;
        const token = Vue.ls.get(window.global_value.TOKEN_KEY);
        switch (error.response.status) {
            case 403:
                handleErr("拒绝访问");
                break;
            case 500:
                console.log("------error.response------", error.response);
                if (
                    token &&
                    (data.message.includes("Token失效") ||
                        data.message.includes("Token超时"))
                ) {
                    handleErr("很抱歉，登录已过期，请重新登录");
                    //执行退出操作
                    store.dispatch("user/clearUserInfo");
                    window.location.reload();
                }
                break;
            case 404:
                handleErr("很抱歉，资源未找到!");
                break;
            case 504:
                handleErr("网络超时");
                break;
            case 401:
                handleErr("很抱歉，登录已过期，请重新登录");
                break;
            default:
                handleErr(data.message);
                break;
        }
    } else if (error.message) {
        if (error.message.includes("timeout")) {
            handleErr("网络超时");
        } else {
            handleErr(error.message);
        }
    }
    return Promise.reject(error);
};

service.interceptors.response.use((response) => {
    return response.data;
}, err);

function handleErr(msg) {
    alert(msg);
}

export default service;
